<template>
  <t-row :gutter="[24, 24]">
    <t-col :flex="4">
      <t-card class="user-info-list" :title="$t('商品信息')" :bordered="false">
        <t-row>
        <t-col :flex="5" class="tdesign-demo-image-viewer__base">
          <t-image-viewer :images="[detailImg]">
            <template #trigger="{ open }">
              <div class="tdesign-demo-image-viewer__ui-image">
                <img alt="test" :src="detailImg" class="tdesign-demo-image-viewer__ui-image--img" />
                <div class="tdesign-demo-image-viewer__ui-image--hover" @click="open">
                  <span>
                    <BrowseIcon size="1.4em" /> 预览
                  </span>
                </div>
              </div>
            </template>
          </t-image-viewer>
        </t-col>
        <t-col :flex="3">
          <!--服务时间选择表-->
          <!--
          <t-table row-key="index" :columns="columns" :data="data" :selected-row-keys="selectedRowKeys"
            :select-on-row-click="selectOnRowClick" :active-row-type="activeRow ? 'single' : undefined" lazy-load
            @select-change="rehandleSelectChange">
          </t-table>
        -->
        </t-col>
        </t-row>
        <template #actions>
          <t-button shape="circle" theme="danger" @click="toShop">
            <rollback-icon />
          </t-button>
          <t-button shape="circle" theme="primary" @click="addCart(detailId)">
            <CartAddIcon />
          </t-button>
          <!--<t-button theme="default" shape="square" variant="text">
            <t-icon name="ellipsis" />
          </t-button>-->
        </template>

        <!--商品描述部分-->
        <t-descriptions :column="4" item-layout="vertical">
          <t-descriptions-item v-for="(item, index) in detailType === 'item' ? GOODS_INFO_LIST : SERVICE_INFO_LIST"
            :key="index" :label="$t(item.title)">
            {{ item.content }}
          </t-descriptions-item>
        </t-descriptions>

      </t-card>
    </t-col>
  </t-row>


  <!---<div class="alert-container" :class="{ show: showAlert }">
    <t-alert v-if="showAlert" theme="success" message="加购成功！" close>
      <template #operation>
        <span @click="toCart"> 去购物车 </span>
      </template>
    </t-alert>
  </div>-->
</template>

<script lang="ts">
import axios from 'axios';
import { BrowseIcon, CartAddIcon, RollbackIcon } from 'tdesign-icons-vue-next';
import { NotifyPlugin } from 'tdesign-vue-next';
import pagination from 'tdesign-vue-next/es/pagination';

export default {
  name: 'UserIndex',
  data() {
    return {
      showAlert: false, // 控制 alert 显示的布尔值
    };
  },
};
// const productList = ref([]);
/* const fetchData = async () => {
  try {
    const { list } = await getProductDetail();
    productList.value = list;
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
}; */
</script>

<script setup lang="ts">
import { LineChart } from 'echarts/charts';
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';
import type { DateRangeValue } from 'tdesign-vue-next';
import { TableProps } from 'tdesign-vue-next';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';

import { getGoodsDetail, getProductCardList, getProductDetail } from '@/api/list';
import { ProductDetail } from '@/api/model/listModel';
import ProductAIcon from '@/assets/assets-product-1.svg';
import ProductBIcon from '@/assets/assets-product-2.svg';
import ProductCIcon from '@/assets/assets-product-3.svg';
import ProductDIcon from '@/assets/assets-product-4.svg';
import router from '@/router';
import { useSettingStore } from '@/store';
import { changeChartsTheme } from '@/utils/color';
import { LAST_7_DAYS } from '@/utils/date';
import { request } from '@/utils/request';

import {  PRODUCT_LIST, TEAM_MEMBERS, USER_INFO_LIST } from './constants';
import { getFolderLineDataSet } from './index';

echarts.use([GridComponent, TooltipComponent, LineChart, CanvasRenderer, LegendComponent]);

let lineContainer: HTMLElement;
let lineChart: echarts.ECharts;
const store = useSettingStore();
const chartColors = computed(() => store.chartColors);
const detailImg = sessionStorage.getItem('img');
const detailName = sessionStorage.getItem('name');
const detailPrice = sessionStorage.getItem('price');
const detailDescribe = sessionStorage.getItem('describe');
const detailType = sessionStorage.getItem('type');
const detailRest = sessionStorage.getItem('rest');
const i = sessionStorage.getItem('i');
const inti = parseInt(i, 10) as number; // 解析成10进制
const detailBegin = [];
const detailEnd = [];
for (let index = 0; index < inti; index++) {
  const key = `timeBegin${index}`;
  detailBegin[index] = sessionStorage.getItem(key);
  detailEnd[index] = sessionStorage.getItem('timeEnd');
}

const url = new URL(window.location.href);
const detailId: string | null = url.searchParams.get('id');

const GOODS_INFO_LIST = [
  {
    title: '名称',
    content: detailName,
    span: 1,
  },
  {
    title: '价格',
    content: detailPrice,
  },
  {
    title: '详情',
    content: detailDescribe,
  },
  {
    title: '类型',
    content: detailType === 'item' ? '一般商品' : detailType === 'service' ? '服务' : '未知类型',
    span: 1,
  },
  {
    title: '库存',
    content: detailRest,
    span: 1,
  },
];
const SERVICE_INFO_LIST = [
  {
    title: '名称',
    content: detailName,
    span: 1,
  },
  {
    title: '价格',
    content: detailPrice,
  },
  {
    title: '详情',
    content: detailDescribe,
  },
  {
    title: '类型',
    content: detailType === 'item' ? '一般商品' : detailType === 'service' ? '服务' : '未知类型',
    span: 1,
  },
  // {
  //   title: '开始时间',
  //   content: detailBegin,
  //   span: 1,
  // },
  // {
  //   title: '结束时间',
  //   content: detailEnd,
  //   span: 1,
  // },
];

// 复选框表格
// const activeRow = ref(false);
// const selectedRowKeys = ref<TableProps['selectedRowKeys']>([]);
// const selectOnRowClick = ref(true);
// const data: TableProps['data'] = [];
// for (let i = 0; i < inti; i++) {
//   data.push({
//     // index: i + 1,
//     beginTime: detailBegin[i],
//     endTime: detailEnd[i],
//   });
// }
// const columns: TableProps['columns'] = [
//   {
//     // title: '单选',
//     // align: 'center',
//     colKey: 'row-select',
//     type: 'single',
//     title: '选择',
//     // 允许单选(Radio)取消行选中
//     checkProps: {
//       allowUncheck: true,
//     },
//     width: 20,
//   },
//   {
//     colKey: 'beginTime',
//     title: '开始时间',
//     width: '50',
//   },
//   {
//     colKey: 'endTime',
//     title: '结束时间',
//     width: '50',
//   },
// ];

// const rehandleSelectChange: TableProps['onSelectChange'] = (value, { selectedRowData }) => {
//   selectedRowKeys.value = value;
//   console.log(value, selectedRowData);
// };


const addCart = async (id: number) => {
  const response = await axios.get('/api/user/addCart', {
    params: {
      id, // 商品id
      number: 1, // 数量
    },
  });
  NotifyPlugin.success({
    title: '成功',
    content: '加入购物车成功！',
    duration: 2000,
  });
};

const toShop = () => {
  router.push('/shop/goods');
};

const onLineChange = (value: DateRangeValue) => {
  lineChart.setOption(
    getFolderLineDataSet({
      dateTime: value as string[],
      ...chartColors.value,
    }),
  );
};

const initChart = () => {
  lineContainer = document.getElementById('lineContainer');
  lineChart = echarts.init(lineContainer);
  lineChart.setOption({
    grid: {
      x: 30, // 默认是80px
      y: 30, // 默认是60px
      x2: 10, // 默认80px
      y2: 30, // 默认60px
    },
    ...getFolderLineDataSet({ ...chartColors.value }),
  });
};

const updateContainer = () => {
  lineChart?.resize({
    width: lineContainer.clientWidth,
    height: lineContainer.clientHeight,
  });
};

onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener('resize', updateContainer, false);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateContainer);
});

const getIcon = (type: string) => {
  switch (type) {
    case 'a':
      return ProductAIcon;
    case 'b':
      return ProductBIcon;
    case 'c':
      return ProductCIcon;
    case 'd':
      return ProductDIcon;
    default:
      return ProductAIcon;
  }
};

watch(
  () => store.brandTheme,
  () => {
    changeChartsTheme([lineChart]);
  },
);

const productList = ref([]);
const dataLoading = ref(true);

// 待修改fetch方式
// 已经弃用
/*
const fetchData = async () => {
  console.log("fetchData")
  try {
    console.log("fetchData1")
    // 请求数据并获取响应
    const response = await axios.get("/api/user/getItems");
    // 从返回的响应中提取数据
    const list = response.data.data.list;
    console.log(list);
    productDetail.value = list[id];
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    // 错误处理
    console.log(e);
  } finally {
    // 数据加载完毕
    dataLoading.value = false;
  }
};

onMounted(() => {
  fetchData();
}); */
</script>

<style lang="less" scoped>
@import './index.less';

.t-descriptions {
  margin-top: 24px;
}

.tdesign-demo-image-viewer__ui-image {
  width: 100%;
  height: 100%;
  display: inline-flex;
  position: relative;
  justify-content: center;
  align-items: center;
  border-radius: var(--td-radius-small);
  overflow: hidden;
}

.tdesign-demo-image-viewer__ui-image--hover {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: var(--td-text-color-anti);
  line-height: 22px;
  transition: 0.2s;
}

.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
  opacity: 1;
  cursor: pointer;
}

.tdesign-demo-image-viewer__ui-image--img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
  position: absolute;
}

.tdesign-demo-image-viewer__ui-image--footer {
  padding: 0 16px;
  height: 56px;
  width: 100%;
  line-height: 56px;
  font-size: 16px;
  position: absolute;
  bottom: 0;
  color: var(--td-text-color-anti);
  background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
  display: flex;
  box-sizing: border-box;
}

.tdesign-demo-image-viewer__ui-image--title {
  flex: 1;
}

.tdesign-demo-popup__reference {
  margin-left: 16px;
}

.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
  cursor: pointer;
}

.tdesign-demo-image-viewer__base {
  width: 600px;
  height: 400px;
  margin: 10px;
  border: 4px solid var(--td-bg-color-secondarycontainer);
  border-radius: var(--td-radius-medium);
}

.alert-container {
  position: fixed;
  /* 固定位置 */
  top: 0;
  /* 距离顶部0 */
  left: 50%;
  /* 水平居中 */
  transform: translateX(-50%);
  /* 水平居中调整 */
  z-index: 1000;
  /* 确保在其他内容之上 */
  transition: all 0.3s ease;
  /* 动画效果 */
  opacity: 0;
  /* 初始时透明 */
  visibility: hidden;
  /* 初始时不可见 */
}

.alert-container.show {
  opacity: 1;
  /* 显示时完全不透明 */
  visibility: visible;
  /* 显示时可见 */
}

</style>
